package com.example.administrator.myview.sql;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 数据库中图片的存储和读取操作
 * Created by Administrator on 2017/11/27.
 */

class ImageSqLite {
    private SQLHelper dbHelper;
    private Context context;

    //要操作数据库操作实例首先得得到数据库操作实例
    ImageSqLite(Context context) {
        this.context=context;
        this.dbHelper = SQLHelper.getIns(context);
    }

    //保存 增加
    void saveImage(int id){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues cv=new ContentValues();
        cv.put("_id", 1);
        cv.put("avatar", bitmapToBytes(context,id));//图片转为二进制
        db.insert("Image", null, cv);
        db.close();
    }

    //读取图片
    byte[] readImage(){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //查询 根据参数查询
        Cursor cur=db.query("Image", new String[]{"_id","avatar"}, null, null, null, null, null);
        byte[] imgData=null;
        if(cur.moveToNext()){
            //将Blob数据转化为字节数组
            imgData=cur.getBlob(cur.getColumnIndex("avatar"));
        }
        return imgData;
    }

    //图片转为二进制数据
    private byte[] bitmapToBytes(Context context, int imageId){
        //将图片转化为位图
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),imageId);
        int size = bitmap.getWidth() * bitmap.getHeight() * 4;
        //创建一个字节数组输出流,流的大小为size
        ByteArrayOutputStream baos= new ByteArrayOutputStream(size);
        try {
            //设置位图的压缩格式，质量为100%，并放入字节数组输出流中
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
            //将字节数组输出流转化为字节数组byte[]
            byte[] imagedata = baos.toByteArray();
            return imagedata;
        }catch (Exception e){
            Log.d("",e.toString());
        }finally {
            try {
                bitmap.recycle();
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new byte[0];
    }
}
